const fs = require('fs'); // 文件模块，用于改文件名字
var iconv = require('iconv-lite'); // 写文件 转码
var path = require('path');
const multer = require('multer'); //解析post文件数据

const easyToday = () => {
    const d = new Date()
    const Y = d.getFullYear()
    const M = d.getMonth() + 1
    const D = d.getDate()
    return Y + (M < 10 ? ('0' + M) : M) + (D < 10 ? ('0' + D) : D)
}
const tempDir = 'upload\\' + easyToday()
const objMulter = multer({dest: 'public\\' + tempDir}); // 添加配置文件到muler对象 上传的文件地址
// 文件获取的模式，为单一模式（当然还有别的模式，比如any,array,fields）
// app.use(objMulter.single('file'));
// app.use(objMulter.any());
const generateMixed = (n) => { // 随机字符
    const chars = [
        '0','1','2','3','4','5','6','7','8','9',
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    ];
    let res = '';
    for(let i = 0; i < n; i ++) {
        let id = Math.ceil(Math.random()*35);
        res += chars[id];
    }
    return res;
};
const resultFormat = (code = 200, content = '', msg = 'null')=> {
    let result = { code: code, data: content, msg: msg };
    return result;
};
module.exports = function (app) {
    // API::文件上传
    app.post('/api/file/upload', objMulter.any(), (req, res) => {
        // res.header('Access-Control-Allow-Origin', '*');
        // res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With');
        // res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
        // res.header('X-Powered-By', ' 3.2.1');
        // var pathNew = req.file.path + pathLib.parse(req.file.originalname).ext
        // 上传接口存在跨域的问题
        const result = {}
        let count = 0
        const callback = () => {
            count += 1;
            if (count < req.files.length) return false;
            res.end(JSON.stringify(resultFormat(200, {res: 1, msg: 'success', path: result})));
        }
        for(var i = 0, l = req.files.length; i < l; i++){
            // console.log(req.files[i].fieldname)
            // ::::::::::::::::
            // fieldname: 'p03',
            // originalname: '2f83ddb9-968b-4c9e-a188-e82eb58a5b9e.png',
            // encoding: '7bit',
            // mimetype: 'image/png',
            // destination: 'public\upload\xxxx(日期)',
            // filename: '8051eb334b0116295c6fc4b8764516a5',
            // path: 'public\upload\xxxx(日期)\\8051eb334b0116295c6fc4b8764516a5',
            // size: 17349
            var pathNew = tempDir + '\\' + new Date().getTime() + '-' + generateMixed(4) + '.jpg';
            fs.rename(req.files[i].path, 'public\\' + pathNew, function (error) {
                callback()
            });
            result[req.files[i].fieldname] = 'http://localhost:4010\\' + pathNew
        }
        return false;
    });
    app.post('/api/file/makeJsonFile', (req, res) => {
        var script = `
            <!-- directive:title 表格插件1.4 改进任礼游表格结构 -->
            <!-- directive:breadcrumb 表格插件1.4 -->
            <div ng-controller='makejson_demo'>
                <div class='yxt14' id='jsonMakeTable'> ${ req.body.codeh } </div>
                <script type='text/javascript'>
                    app.controller('makejson_demo', function($scope, $rootScope, $http, $timeout, $state, $uibModal, yxtable14, mock, $API, $compile) { ${ req.body.codea } ${ req.body.codej }
                    })
                </script>
            </div>
            `;
        var localPath = '../project.xianjs_be_angular/src/tpl/table/yxtable15.html';
        var buffer = iconv.encode(script, 'utf8'); // 这里调用encode函数进行转码
        fs.writeFile(localPath, buffer, (error)=>{
            let result;
            if (error) {
                result = resultFormat(200, {res: 0, msg: error || 'failed'});
            } else {
                result = resultFormat(200, {res: 1, msg: 'success'});
            }
            res.end(JSON.stringify(result));
        });
    });
    app.post('/api/file/writeFile', (req, res) => {
        var localPath = req.body.file;
        var buffer = iconv.encode(req.body.code, 'utf8'); // 这里调用encode函数进行转码
        var sourceFile = path.join(__dirname, '../../www/', localPath+ '.txt');
        var destPath = path.join(__dirname, '../../www/', localPath + '.' + (new Date).getTime() + '.txt');
        var readStream = fs.createReadStream(sourceFile);
        var writeStream = fs.createWriteStream(destPath);
        readStream.pipe(writeStream);
        fs.writeFile(sourceFile, buffer, (error)=>{
            let result;
            if (error) {
                result = resultFormat(200, {res: 0, msg: error || 'failed'});
            } else {
                result = resultFormat(200, {res: 1, msg: 'success'});
            }
            res.end(JSON.stringify(result));
        });
    });
    app.post('/api/file/download1', function (req, res) {
        //第一种方式
        //var f='F:/ftproot/NW.js.docx'
        //var f='f:/ftproot/我是中文的语言.txt'
        ////var f = req.params[0]
        //f = path.resolve(f)
        //console.log('Download file: %s', f)
        //res.download(f)
        //第二种方式
        var path = 'E:/jiake.mp4';
        var f = fs.createReadStream(path);
        res.writeHead(200, {
            'Content-Type': 'application/force-download',
            'Content-Length': '296000',
            'Content-Disposition': 'attachment filename=jiake.mp4'
        });
        f.pipe(res);
    });
    app.post('/api/file/download2',function(req, res){
        const currDir = 'E:/'; // path.normalize(req.query.dir)
        const fileName = 'jiake.mp4'; // req.query.name
        const currFile = path.join(currDir, fileName);
        fs.exists(currFile, function(exist) {
            if(exist){
                res.set({
                    'Content-type':'application/octet-stream',
                    'Content-Length': '296000',
                    'Content-Disposition':'attachmentfilename=' + encodeURI(fileName)
                });
                const fReadStream = fs.createReadStream(currFile);
                fReadStream.on('data', (chunk) => res.write(chunk,'binary'));
                fReadStream.on('end', () => { res.end(); });
            }else{
                res.set('Content-type','text/html');
                res.send('file not exist!');
                res.end();
            }
        });
    });
    app.get('/api/file/download',function(req, res){
        const currDir = 'E:/'; // path.normalize(req.query.dir)
        // const fileName = '123.xlsx' // req.query.name
        const fileName = 'jiake.mp4'; // req.query.name
        const currFile = path.join(currDir, fileName);
        const size = fs.statSync(currFile).size;
        res.set({
            // 'Content-type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-type':'video/mpeg4',
            'Content-Length': size,
            'Content-Disposition':'attachment; filename=' + encodeURI(fileName)
        });
        const fReadStream = fs.createReadStream(currFile);
        fReadStream.on('data', (chunk) => res.write(chunk,'binary'));
        fReadStream.on('end', () => { res.end(); });
    });
};
